import {
  app,
  shell,
  BrowserWindow,
  ipcMain,
  screen,
  Tray,
  Menu,
  dialog,
  globalShortcut
} from 'electron'
import path, { join } from 'path'
import fs from 'fs'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
// import icon from '../../resources/icon.png?asset'
// import icon from '/@/assets/icons/tray.png'
import icon from '../renderer/src/assets/icons/tray.png'

const loginWidth = 320
const loginHeight = 324
const mainWidth = 900
const mainHeight = 670
const deviationDistance = 50
let initMainPosition = { x: 0, y: 0 }
let isLogged = false
let loginWindow
let mainWindow
const createLoginWindow = () => {
  loginWindow = new BrowserWindow({
    icon,
    // ...(process.platform === 'linux' ? { icon } : {}),
    width: loginWidth,
    height: loginHeight,
    autoHideMenuBar: true,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      enableRemoteModule: true
    },
    resizable: false,
    frame: false,
    titleBarStyle: 'hidden'
  })
  loginWindow.on('ready-to-show', () => {
    loginWindow.show()
  })
  loginWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    loginWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    loginWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}
const createMainWindow = () => {
  isLogged = true
  mainWindow = new BrowserWindow({
    icon,
    // ...(process.platform === 'linux' ? { icon } : {}),
    width: mainWidth,
    height: mainHeight,
    // show: false,
    autoHideMenuBar: true,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      enableRemoteModule: true
    },
    // backgroundColor: '#fff',
    resizable: false,
    frame: false,
    // transparent: true,
    titleBarStyle: 'hidden'
  })
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  //   mainWindow.webContents.openDevTools()

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}
const createNewWindow = () => {
  const newWindow = new BrowserWindow({
    icon,
    // ...(process.platform === 'linux' ? { icon } : {}),
    width: mainWidth,
    height: mainHeight,
    // show: false,
    autoHideMenuBar: true,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      enableRemoteModule: true
    },
    resizable: false,
    frame: false,
    titleBarStyle: 'hidden'
  })
  const { deviationLeft, deviationTop } = setWindowPosition()
  // 每新增一个窗口，将新窗口位置偏移
  newWindow.setPosition(deviationLeft, deviationTop)
  newWindow.on('ready-to-show', () => {
    newWindow.show()
  })
  newWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    newWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    newWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}
// 计算新窗口定位点
const setWindowPosition = () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize
  const deviationCount = BrowserWindow.getAllWindows().length - 1
  const deviationLeft = (width - mainWidth) / 2 + deviationDistance * deviationCount
  const deviationTop = (height - mainHeight) / 2 + deviationDistance * deviationCount
  console.log(deviationCount, 'deviationCount')
  return { deviationLeft, deviationTop }
}
// 创建托盘
const createDockTray = () => {
  const tray = new Tray(path.join(__dirname, '../../src/renderer/src/assets/icons/tray.png'))
  //   const tray = new Tray('../renderer/src/assets/icons/tray.png')
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示',
      // type: "normal",
      click: () => {
        if (isLogged) {
          mainWindow.show()
        } else {
          loginWindow.show()
        }
      }
    },
    {
      label: '最小化',
      click: () => {
        const browserList = BrowserWindow.getAllWindows()
        browserList.forEach((item) => {
          item.minimize()
        })
      }
    },
    {
      label: '退出',
      click: () => {
        app.quit()
      }
    }
  ])
  tray.setToolTip('这是一个托盘')
  tray.setContextMenu(contextMenu)
}
// 注册全局快捷键
const createGlobalShortcut = () => {
  commandList.forEach((item) => {
    const { command, callback } = item
    globalShortcut.register(command, () => {
      callback()
    })
  })
}
// 关闭当前窗口
const closeActiveWindow = () => {
  const activeWindow = BrowserWindow.getFocusedWindow()
  if (activeWindow) {
    activeWindow.close()
  }
}
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createLoginWindow()
  createDockTray()
  createGlobalShortcut()
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createLoginWindow()
  })
  // 登录后关闭登录窗口 新建主窗口
  ipcMain.on('is-login', (event, arg) => {
    loginWindow.close()
    console.log('-----------------------')
    createMainWindow(false)
  })
  // 窗口最小化
  ipcMain.on('window-minimize', (event, arg) => {
    if (arg) {
      mainWindow.minimize()
    } else {
      loginWindow.minimize()
    }
  })
  // 从任务栏中移除，在托盘中展示
  ipcMain.on('window-hide', (event, arg) => {
    if (isLogged) {
      mainWindow.hide()
    } else {
      loginWindow.hide()
    }
  })
  // 窗口拖动时判断是主窗口/登录窗口修改其位置
  ipcMain.on('drag-render', (event, arg) => {
    const { offsetX, offsetY, mainDrag } = arg
    const currentWindow = mainDrag ? mainWindow : loginWindow
    const position = currentWindow.getPosition()
    currentWindow.setPosition(position[0] + offsetX, position[1] + offsetY, true)
  })
  // 切换全屏或还原
  ipcMain.on('toggle-full-screen', (event, arg) => {
    const { width, height } = screen.getPrimaryDisplay().workAreaSize
    const { x, y, width: w, height: h } = mainWindow.getBounds()
    if (w === width && h === height) {
      mainWindow.setBounds({
        x: initMainPosition.x,
        y: initMainPosition.y,
        width: mainWidth,
        height: mainHeight
      })
    } else {
      initMainPosition = { x, y }
      mainWindow.setBounds({ x: 0, y: 0, width, height })
    }
  })
  // 监听菜单栏点击
  ipcMain.on('click-menu', (event, arg) => {
    const target = commandList.find((item) => item.command === arg)
    if (target) {
      const { callback } = target
      callback()
    }
  })
})
// 打开读取文件窗口
const openFile = () => {
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
        { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }
      ]
    })
    .then((result) => {
      //   console.log(result, '123')
      if (!result.canceled) {
        mainWindow.webContents.send('switchToFile')
        const filePath = result.filePaths
        const list = []
        const readFileFun = async (filePath) => {
          for (const path of filePath) {
            const fileContent = await fs.promises.readFile(path)
            const data = fileContent.toString('base64')
            list.push(data)
          }
          mainWindow.webContents.send('openFileMes', list)
        }
        setTimeout(() => {
          readFileFun(filePath)
        }, 500)
      }
    })
}
const commandList = [
  {
    command: 'Ctrl+Shift+N',
    callback: () => {
      createNewWindow()
    }
  },
  {
    command: 'Ctrl+Shift+W',
    callback: () => {
      closeActiveWindow()
    }
  },
  {
    command: 'Ctrl+O',
    callback: () => {
      openFile()
    }
  }
]
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
